﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MetroTube.BusinessLogic
{
    public class VideoExtrapolation
    {

        private static readonly Regex YouTubeUrlRegex = new Regex(@"youtu(?:\.be|be\.com)/(?:(.*)v(/|=)|(.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

        private static readonly string[] NameSeparator = { "<meta name=\"title\" content", ">" };
        private static readonly string[] LinkSeparatorFirstStep = { "url=", @"\u0026itag" };
        private static readonly string[] LinkSeparatorSecondStep = { @"\u0026quality", @"\u0026fallback", "type=video", ";+" };

        private static YouTubeHtmlWebPage _htmlWebPage;

        public static YouTubeVideo GetVideoExtrapolation(YouTubeHtmlWebPage htmlWebPage)
        {
            if (htmlWebPage == null)
                return null;

            _htmlWebPage = htmlWebPage;

            return new YouTubeVideo(Id, Name, ImgUrl, Links);
        }


        private static string Id
        {
            get
            {
                string id = string.Empty;

                Match idMatch = YouTubeUrlRegex.Match(_htmlWebPage.Url);

                if (idMatch.Success)
                    id = idMatch.Groups[(idMatch.Groups.Count - 1)].Value;

                return id;
            }
        }

        private static string Name
        {
            get
            {
                string name = string.Empty;
                string sourceCode = _htmlWebPage.SourceCode;

                string[] result = sourceCode.Split(NameSeparator, StringSplitOptions.RemoveEmptyEntries);

                foreach (string s in result)
                {
                    if (s.StartsWith("="))
                    {
                        name = s.Replace("=", "").Replace("\"", "").Replace("&#39;", "'").Replace("&quot;", "\"");
                        break;
                    }
                }

                return name;
            }
        }

        private static string ImgUrl
        {
            get
            {
                return String.Format("http://img.youtube.com/vi/{0}/0.jpg", Id);
            }
        }

        private static YouTubeVideoLink[] Links
        {
            get
            {
                List<YouTubeVideoLink> videoUrl = new List<YouTubeVideoLink>();

                string sourceCode = _htmlWebPage.SourceCode;

                string[] resultFirstStep = sourceCode.Split(LinkSeparatorFirstStep, StringSplitOptions.RemoveEmptyEntries);

                string link = null;
                string quality = null;
                string type = null;


                foreach (string s in resultFirstStep)
                {
                    if (s.StartsWith("http%3A%2F%2Fo-o"))
                    {
                        string rawLink = s.Replace("%3A", ":").Replace("%2F", "/").Replace("%3F", "?").Replace("%3D", "=").Replace("%252C", ",").Replace("%26", "&").Replace("%3B", ";").Replace("%22", "\"").Replace("%2C", ",");

                        string[] resultSecondStep = rawLink.Split(LinkSeparatorSecondStep, StringSplitOptions.RemoveEmptyEntries);

                        foreach (string ss in resultSecondStep)
                        {
                            //Console.WriteLine(ss);
                            //Console.WriteLine("---------------------------------------------------------------------------------------");

                            switch (ss.Substring(0, 1))
                            {
                                case "h":

                                    link = ss;

                                    if (link.EndsWith(@"\u0026"))
                                        link = link.Substring(0, link.Length - 6);

                                    break;

                                case "=":

                                    quality = ss.Substring(1);

                                    if (quality.EndsWith(","))
                                        quality = quality.Substring(0, quality.Length - 1);

                                    break;

                                case "/":

                                    type = ss.Substring(1);

                                    if (type.StartsWith("x-"))
                                        type = type.Substring(2);

                                    break;

                                default:
                                    break;
                            }

                        }

                        videoUrl.Add(new YouTubeVideoLink(link, quality, type));

                    }
                }

                return videoUrl.ToArray<YouTubeVideoLink>();
            }
        }
    }
}
